package com.wyl.salary.ui.viewmodel

import android.app.Application
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
import com.wyl.salary.pojo.SalaryBean
import com.wyl.salary.pojo.SalaryBean_
import com.wyl.salary.repository.ObjectBox
import com.wyl.salary.utils.format
import com.wyl.salary.utils.toDate
import java.text.ParseException
import java.util.*

private const val TAG = "AddSalaryViewModel"

class AddSalaryViewModel(app: Application) : AndroidViewModel(app) {
    private val sp = app.getSharedPreferences("salary", 0)

    var date by mutableStateOf(Date().format())
    var hours by mutableStateOf("")
    var salary by mutableStateOf(sp.getString("defaultSalary", "")!!)
    var tipping by mutableStateOf("")
    var remarks by mutableStateOf("")

    var id = -1L

    fun addSalary(onSuccess: () -> Unit, onError: (String) -> Unit) {
        var bean: SalaryBean? = null
        try {
            bean = SalaryBean(
                date = date.toDate(),
                hours = hours.toDouble(),
                salary = salary.toDouble(),
                tipping = tipping.toDouble(),
                remarks = remarks
            )
            if (id != -1L) {
                bean.id = id
            }
        } catch (e: NumberFormatException) {
            onError("请填写正确的数字")
        } catch (e: ParseException) {
            onError("日期格式不正确")
        }
        bean?.let {
            val put = ObjectBox.salaryBox.put(it)
            Log.d(TAG, "addSalary: $put")
            onSuccess()
        }
    }

    fun delSalary() {
        ObjectBox.salaryBox.remove(id)
    }

    fun querySalary(sid: Long) {
        ObjectBox.salaryBox.query().equal(SalaryBean_.id, sid).build().use { query ->
            query.findUnique()?.let {
                id = sid
                date = it.date.format()
                hours = it.hours.toString()
                salary = it.salary.toString()
                tipping = it.tipping.toString()
                remarks = it.remarks
            }
        }
    }
}